﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using VietPublisher.BSL.BK;
using VietPublisher.Membership;
using VietPublisher.BaseProject.Utils.Miscellaneous;
using System.Web;
using System.Web.Security;


namespace VietPublisher.Web.Controls
{
    public static class ControllerExtensions
    {
        #region Controllers & View

        public static string ActionName(this ViewContext view)
        {
            return view.Controller.ValueProvider.GetValue("action").RawValue.ToString();
        }

        public static string ControllerName(this ViewContext view)
        {
            return view.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
        }

        #endregion

        #region User & Group info


        static public string EmailDomainName(this Controller controller)
        {
            return ConfigurationManager.AppSettings["DOMAIN_NAME"];
        }

        static public string EmailDomainName(this ViewContext view)
        {
            return ConfigurationManager.AppSettings["DOMAIN_NAME"];
        }

        static public string UploadImagePath(this Controller controller)
        {
            string relPath = string.Format("/Content/TmpFiles/{0}/Images", controller.CurrentUser().Email);
            string folderPath = controller.ControllerContext.HttpContext.Server.MapPath(relPath);
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            return relPath;
        }

        static public string UploadImagePath(this ViewContext viewContext)
        {
            string relPath = string.Format("/Content/TmpFiles/{0}/Images", viewContext.Controller.CurrentUser().Email);
            string folderPath = viewContext.HttpContext.Server.MapPath(relPath);
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            return relPath;
        }

        static public Guid GetUserId(this ControllerBase controller, string userName)
        {

            MembershipEntities EntityContext = new MembershipEntities();

            userName = userName.ToLower();

            VietPublisher.Membership.aspnet_Users user = null;
            try
            {
                user = EntityContext.aspnet_Users.FirstOrDefault(item => item.LoweredUserName == userName);
            }
            catch (Exception)
            {
                int count = 1;
                while (count < 10)
                {
                    System.Threading.Thread.Sleep(1000);
                    count++;
                }

                try
                {
                    user = EntityContext.aspnet_Users.FirstOrDefault(item => item.LoweredUserName == userName);
                }
                catch (Exception exception)
                {
                    LogMessage(controller, exception.Message);
                    LogMessage(controller, exception.StackTrace);
                }
            }

            if (user != null) return user.UserId;
            return Guid.Empty;
        }

        static private void RetryConnection(this ControllerBase controller)
        {
            try
            {
                VIETPUBLISHEREntities EntityContext = new VIETPUBLISHEREntities();

                if (EntityContext.Connection.State == System.Data.ConnectionState.Broken)
                {
                    EntityContext.Connection.Close();
                }

                if (EntityContext.Connection.State == System.Data.ConnectionState.Closed)
                {
                    EntityContext.Connection.Open();
                }
            }
            catch (Exception ex)
            {
                LogMessage(controller, ex.Message);
                LogMessage(controller, ex.StackTrace);
            }
        }

        static public Guid CurrentUserId(this ControllerBase controller)
        {
            return GetUserId(controller, controller.CurrentUserName());
        }

        static public Guid CurrentUserId(this ViewContext view)
        {
            return GetUserId(view.Controller, view.Controller.CurrentUserName());
        }

        static public string CurrentUserName(this ControllerBase controller)
        {
            string userName = string.Empty;
            //if (controller.ControllerContext != null &&
            //    controller.ControllerContext.HttpContext != null &&
            //    controller.ControllerContext.HttpContext.User != null &&
            //    controller.ControllerContext.HttpContext.User.Identity.IsAuthenticated
            //    && !string.IsNullOrEmpty(controller.ControllerContext.HttpContext.User.Identity.Name))
            //{
            //    userName = controller.ControllerContext.HttpContext.User.Identity.Name;
            //}
            //else if (controller.ControllerContext != null &&
            //    controller.ControllerContext.RequestContext != null &&
            //    controller.ControllerContext.RequestContext.HttpContext != null &&
            //    controller.ControllerContext.RequestContext.HttpContext.User != null &&
            //    controller.ControllerContext.RequestContext.HttpContext.User.Identity != null &&
            //    controller.ControllerContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            //{
            //    userName = controller.ControllerContext.RequestContext.HttpContext.User.Identity.Name;
            //}
            try
            {
                //userName = controller.ControllerContext.HttpContext.User.Identity.Name;

              //  userName = HttpContext.Current.User.Identity.Name;
                if (string.IsNullOrEmpty(userName))
                {
                    userName = HttpContext.Current.Session[DConst.userName] != null ? HttpContext.Current.Session[DConst.userName].ToString() : "";
                }
                //todo triet fix lay name of user
            }
            catch
            {
            }

            return userName;
        }

        static public vw_BK_MembershipUsers CurrentUser(this ControllerBase controller)
        {
            MembershipEntities EntityContext = new MembershipEntities();

            Guid userId = controller.CurrentUserId();
            return EntityContext.vw_BK_MembershipUsers.FirstOrDefault(p => p.UserId == userId);
        }

        static public string ToAccountName(this ControllerBase controller, Guid userId)
        {
            VIETPUBLISHEREntities EntityContext = new VIETPUBLISHEREntities();

            var emp = EntityContext.T_BK_UserExtend.FirstOrDefault(p => p.UserID == userId);
            return emp != null ? emp.Name : string.Empty;
        }

        #endregion

        #region Menu

        //static public int CurrentMenuId(this ViewContext viewContext)
        //{
        //    return viewContext.Controller.CurrentMenuId();
        //}

        //static public int CurrentMenuId(this ControllerBase controller)
        //{
        //    var menu = controller.CurrentMenu();
        //    if (menu != null)
        //    {
        //        return menu.MenuID;
        //    }
        //    return 0;
        //}

        //static public T_CO_Menu CurrentMenu(this ViewContext viewContext)
        //{
        //    return viewContext.Controller.CurrentMenu();
        //}

        //static public T_CO_Menu CurrentMenu(this ControllerBase controller)
        //{
        //    VIETPUBLISHEREntities EntityContext = new VIETPUBLISHEREntities();

        //    var controllerName = controller.ValueProvider.GetValue("controller").RawValue.ToString();
        //    var actionName = controller.ValueProvider.GetValue("action").RawValue.ToString();
        //    if (controllerName == null || actionName == null) return null;

        //    var menu = EntityContext.T_CO_Menu.FirstOrDefault(item => item.Action == actionName &&
        //                                                            item.Controller == controllerName);
        //    if (menu != null)
        //    {
        //        string temp = menu.Controller;
        //    }
        //    return menu;


        //}


        //static public en_CO_MenuPermission[] GetPermitMenus(this ViewContext viewContext)
        //{

        //    en_CO_MenuPermission[] allMenus = null;
        //    var menus = viewContext.HttpContext.Session["PermitMenus"];
        //    if (menus != null)
        //    {
        //        allMenus = menus as en_CO_MenuPermission[];
        //    }
        //    else
        //    {
        //        VIETPUBLISHEREntities EntityContext = new VIETPUBLISHEREntities();
        //        allMenus = EntityContext.FN_CO_GetAllMenuPermission(viewContext.CurrentUserId(), "ko-KR").ToArray();

        //        viewContext.HttpContext.Session["PermitMenus"] = allMenus;
        //    }

        //    return allMenus;
        //}

        #endregion

        #region Languages

        /// <summary>
        /// Get current saved language
        /// </summary>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static string CurrentLanguage(this ControllerBase controller)
        {
            if (controller.ControllerContext.HttpContext.Session["Language"] == null)
            {
                controller.ControllerContext.HttpContext.Session["Language"] = "en-US"; //System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            }

            string cuName = controller.ControllerContext.HttpContext.Session["Language"].ToString();

            if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != cuName)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cuName);
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cuName);
            }

            return cuName;
        }

        #endregion

        #region Util


        /// <summary>
        /// Log error message to log file
        /// </summary>
        /// <param name="ex"></param>
        public static void LogMessage(this ControllerBase controller, string message)
        {
            System.IO.StreamWriter sw = null;
            try
            {
                string logDir = controller.ControllerContext.HttpContext.Server.MapPath("~") + "\\Log";
                if (!Directory.Exists(logDir))
                {
                    Directory.CreateDirectory(logDir);
                }
                string logFile = logDir + string.Format("\\{0:yyyyMMdd}.log", DateTime.Today);
                if (!System.IO.File.Exists(logFile))
                    System.IO.File.Create(logFile).Close();
                sw = new System.IO.StreamWriter(logFile, true);
                sw.WriteLine(string.Format("[{0:yyyy-MM-dd HH:mm:ss} {1}] ", DateTime.Now, message));
                sw.Flush();
            }
            catch
            {
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }

            }
        }


        #endregion

    }
}
